from django.db import models
from op_drf.base import BaseModel
from op_drf.base_user import AbstractBaseUser, BaseUserManager
from uuid import uuid4
import os, uuid
from datetime import timezone

# Create your models here.

"""
新建附件存储数据表
"""


def files_path(instance, filename):
    return os.path.join(
        ["system", timezone.now().strftime("%Y-%m-%d"), str(uuid.uuid4()) + os.path.splitext(filename)[-1]]
    )


class SaveFile(BaseModel):
    name = models.TextField(verbose_name="文件名称", null=True, blank=True)
    type = models.CharField(max_length=200, verbose_name="文件类型", null=True, blank=True)
    size = models.CharField(max_length=64, verbose_name="文件大小", null=True, blank=True)
    address = models.CharField(max_length=16, verbose_name="存储位置", null=True, blank=True)  # 本地、阿里云、腾讯云..
    source = models.CharField(max_length=16, verbose_name="文件来源", null=True, blank=True)  # 导出、用户上传.
    oss_url = models.CharField(max_length=200, verbose_name="OSS地址", null=True, blank=True)
    status = models.BooleanField(default=True, verbose_name="文件是否存在")
    file = models.FileField(
        verbose_name="文件URL",
        upload_to=files_path,
    )
    model = models.CharField(max_length=100, null=True, verbose_name="关联模型")
    relation_id = models.IntegerField(null=True, verbose_name="关联字段")
    model_type = models.CharField(max_length=100, null=True, verbose_name="类型")
    info = models.TextField(verbose_name="文件信息", null=True, blank=True)

    class Meta:
        db_table = "sys_savefile"
        verbose_name = "文件管理"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.name}"


# 用户数据表
class UserProfile(AbstractBaseUser, BaseModel):
    USER_TYPE_CHOICES = (
        (0, "后台用户"),
        (1, "前台用户"),
        (2, "供应商用户"),
    )
    objects = BaseUserManager()
    username = models.CharField(max_length=150, null=True, verbose_name="用户账号")
    secret = models.CharField(max_length=255, default=uuid4, verbose_name="加密秘钥")
    email = models.CharField(max_length=255, verbose_name="邮箱", null=True, blank=True)
    mobile = models.CharField(max_length=255, verbose_name="电话", null=True, blank=True)
    avatar = models.TextField(verbose_name="头像", null=True, blank=True)
    name = models.CharField(max_length=40, verbose_name="姓名")
    gender = models.CharField(max_length=8, verbose_name="性别", null=True, blank=True)
    remark = models.TextField(verbose_name="备注", null=True)
    user_sort = models.IntegerField(verbose_name="用户排序", null=True, blank=True)
    user_type = models.IntegerField(default=1, verbose_name="用户类型")
    wx_name = models.CharField(max_length=100, null=True, blank=True, verbose_name="企业微信账号", help_text="企业微信账号")
    post = models.ManyToManyField(to="vadmin.Post", verbose_name="关联岗位", db_constraint=False)
    role = models.ManyToManyField(to="vadmin.Role", verbose_name="关联角色", db_constraint=False)
    dept = models.ForeignKey(
        to="vadmin.Dept",
        verbose_name="归属部门",
        on_delete=models.CASCADE,
        db_constraint=False,
        null=True,
        blank=True,
    )

    employee = models.ForeignKey(
        to="vadmin.Em_Basic",
        verbose_name="关联员工",
        on_delete=models.CASCADE,
        db_constraint=False,
        null=True,
        blank=True,
    )
    is_resign = models.BooleanField(verbose_name="是否已离职", help_text="是否已离职", default=False, blank=False, null=False)

    class Meta:
        db_table = "sys_userprofile"

class Post(BaseModel):
    """
    岗位
    """
    postName = models.CharField(null=False, max_length=64, verbose_name="岗位名称")
    postCode = models.CharField(max_length=32, verbose_name="岗位编码", null=True, blank=True)
    postSort = models.IntegerField(verbose_name="岗位顺序")
    status = models.BooleanField(verbose_name="岗位状态",help_text="岗位状态",null=False)
    remark = models.TextField(verbose_name="备注", help_text="备注", null=True, blank=True)
    is_delete = models.BooleanField(verbose_name="是否删除", help_text="是否删除", default=False, blank=False, null=False)

    class Meta:
        db_table = "sys_post"
        verbose_name = "岗位管理"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.postName}"


class Role(BaseModel):
    """
    角色
    """

    DATASCOPE_CHOICES = (
        ("1", "全部数据权限"),
        ("2", "自定数据权限"),
        ("3", "本部门数据权限"),
        ("4", "本部门及以下数据权限"),
        ("5", "仅本人数据权限"),
    )
    roleName = models.CharField(max_length=64, verbose_name="角色名称")
    roleKey = models.CharField(max_length=64, verbose_name="权限字符")
    roleSort = models.IntegerField(verbose_name="角色顺序")
    # 0:停用 1:启用
    status = models.CharField(max_length=8, verbose_name="角色状态")
    admin = models.BooleanField(default=False, verbose_name="是否为admin")
    dataScope = models.CharField(
        max_length=8,
        default="1",
        choices=DATASCOPE_CHOICES,
        verbose_name="权限范围",
    )
    remark = models.TextField(verbose_name="备注", help_text="备注", null=True, blank=True)
    dept = models.ManyToManyField(to="vadmin.Dept", verbose_name="数据权限-关联部门", db_constraint=False)
    menu = models.ManyToManyField(to="vadmin.Menu", verbose_name="关联菜单权限", db_constraint=False)
    domainFields = models.CharField(max_length=64, verbose_name="域字段", null=True, blank=True)
    modelKey = models.CharField(max_length=150, verbose_name="模型字符", null=True, blank=True)

    class Meta:
        db_table = "sys_Role"
        verbose_name = "角色管理"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.roleName}"


class Dept(BaseModel):
    """
    部门
    """

    deptName = models.CharField(max_length=64, verbose_name="部门名称")
    orderNum = models.FloatField(verbose_name="显示排序", default=0)
    owner = models.CharField(max_length=32, verbose_name="负责人", null=True, blank=True)
    phone = models.CharField(max_length=32, verbose_name="联系电话", null=True, blank=True)
    email = models.CharField(max_length=32, verbose_name="邮箱", null=True, blank=True)
    status = models.CharField(max_length=8, verbose_name="部门状态", null=True, blank=True)
    dept_classify = models.CharField(verbose_name="部门分类", max_length=40, null=True, blank=True, help_text="部门分类")
    DEPART_TYPE_CHOICE = [
        ("00", "未分类"),
        ("01", "经营分院"),
        ("02", "合作分院"),
        ("03", "公司法人"),
        ("04", "职能部门"),
        ("05", "集团总院"),
    ]
    depart_type = models.CharField(
        verbose_name="部门类型",
        help_text="部门类型",
        max_length=16,
        default="00",
        choices=DEPART_TYPE_CHOICE,
        null=True,
        blank=True,
    )

    parentId = models.ForeignKey(
        to="vadmin.Dept",
        on_delete=models.CASCADE,
        default=False,
        verbose_name="上级部门",
        db_constraint=False,
        null=True,
        blank=True,
    )

    class Meta:
        db_table = "sys_dept"
        verbose_name = "部门管理"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.deptName}"


class Station(BaseModel):
    """
    职务
    """

    station_name = models.CharField(verbose_name="职务名称", max_length=16, help_text="职务名称")

    def __str__(self):
        return self.station_name

    class Meta:
        db_table = "sys_station"
        # 站点管理显示名称
        verbose_name = "职务信息"
        # 站点管理复数显示名称
        verbose_name_plural = "职务信息"


class Menu(BaseModel):
    """
    菜单
    """

    # MENU_TYPE_CHOICES = (
    #     ("0", "目录"),
    #     ("1", "菜单"),
    #     ("2", "按钮"),
    # )
    # METHOD_CHOICE = (
    #     ('GET', 'GET'),
    #     ('POST', 'POST'),
    #     ('PUT', 'PUT'),
    #     ('PATCH', 'PATCH'),
    #     ('DELETE', 'DELETE'),
    #     ('HEAD', 'HEAD'),
    #     ('OPTIONS', 'OPTIONS'),
    #     ('TRACE', 'TRACE'),
    # )
    parentId = models.ForeignKey(
        to="Menu",
        on_delete=models.CASCADE,
        verbose_name="上级菜单",
        null=True,
        blank=True,
        db_constraint=False,
        related_name="child_menus",
    )

    menuType = models.CharField(max_length=8, verbose_name="菜单类型")
    icon = models.CharField(max_length=64, verbose_name="菜单图标", null=True, blank=True)
    name = models.CharField(max_length=64, verbose_name="菜单名称")
    orderNum = models.IntegerField(verbose_name="显示排序")
    isFrame = models.CharField(max_length=8, verbose_name="是否外链")
    web_path = models.CharField(max_length=128, verbose_name="前端路由地址", null=True, blank=True)
    component_path = models.CharField(max_length=128, verbose_name="前端组件路径", null=True, blank=True)
    interface_path = models.CharField(max_length=256, verbose_name="后端接口路径", null=True, blank=True)
    interface_method = models.CharField(max_length=16, default="GET", verbose_name="接口请求方式")
    perms = models.CharField(max_length=256, verbose_name="权限标识", null=True, blank=True)
    meta = models.CharField(max_length=500, verbose_name="其他参数", null=True, blank=True)
    status = models.CharField(max_length=8, verbose_name="菜单状态")
    visible = models.CharField(max_length=8, verbose_name="显示状态")
    isCache = models.CharField(max_length=8, verbose_name="是否缓存")

    # @classmethod
    # def get_interface_dict(cls):
    #     """
    #     获取所有接口列表
    #     :return:
    #     """
    #     try:
    #         interface_dict = (
    #             cache.get("permission_interface_dict", {}) if getattr(settings, "REDIS_ENABLE", False) else {}
    #         )
    #     except:
    #         interface_dict = {}
    #     if not interface_dict:
    #         for ele in Menu.objects.filter(~Q(interface_path=""), ~Q(interface_path=None), status="1").values(
    #             "interface_path", "interface_method"
    #         ):
    #             if ele.get("interface_method") in interface_dict:
    #                 interface_dict[ele.get("interface_method", "")].append(ele.get("interface_path"))
    #             else:
    #                 interface_dict[ele.get("interface_method", "")] = [ele.get("interface_path")]
    #         if getattr(settings, "REDIS_ENABLE", False):
    #             cache.set("permission_interface_dict", interface_dict, 84600)
    #     return interface_dict
    #
    # @classmethod
    # def delete_cache(cls):
    #     """
    #     清空缓存中的接口列表
    #     :return:
    #     """
    #     if getattr(settings, "REDIS_ENABLE", False):
    #         cache.delete("permission_interface_dict")
    #
    # def get_children(self):
    #     pass

    class Meta:
        db_table = "sys_menu"
        verbose_name = "菜单管理"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.name}"


class Em_Basic(BaseModel):
    """
    员工信息
    """

    emp_id = models.CharField(verbose_name="员工工号", max_length=16, null=True, help_text="员工工号")
    emp_name = models.CharField(verbose_name="员工姓名", max_length=32, null=False, help_text="员工姓名")

    gender = models.CharField(verbose_name="员工性别", max_length=6, default="男", null=True, blank=True)
    emp_type = models.CharField(verbose_name="员工类别", max_length=6, default="正式", null=True, blank=True)
    # # 使用ethnic表的数据
    # ethnic = models.ForeignKey(
    #     "ehr.Ethnic",
    #     verbose_name="民族",
    #     on_delete=models.CASCADE,
    #     null=True,
    #     blank=True,
    #     help_text="民族",
    # )
    id_card = models.CharField(
        verbose_name="身份证号码", max_length=20, null=True, blank=True, unique=True, help_text="身份证号码"
    )
    month_birth = models.DateField(verbose_name="出生日期", max_length=20, null=True, blank=True, help_text="出生日期")
    join_date = models.DateField(verbose_name="入职时间", max_length=20, null=True, blank=True, help_text="入职时间")
    political_status = models.CharField(verbose_name="政治面貌", max_length=16, default="群众", blank=True)
    highest_degree = models.CharField(verbose_name="文化程度", max_length=8, default="本科", blank=True)
    reg_title = models.CharField(verbose_name="注册资质", max_length=12, default="普通员工", blank=True)
    certificate = models.TextField(verbose_name="证书名称", blank=True, null=True, help_text="证书名称")
    # dept = models.ManyToManyField("ehr.Department", verbose_name="部门名称", related_name="embic_dept")
    dept_names = models.TextField(verbose_name="部门名称", null=True, blank=True)
    # station = models.ManyToManyField("ehr.Station", verbose_name="职务名称", through="Em_Basic_Station")
    # rank_title = models.ForeignKey(
    #     "ehr.EmBaseRank",
    #     verbose_name="人员职级",
    #     on_delete=models.CASCADE,
    #     null=True,
    #     blank=True,
    #     help_text="人员职级",
    # )
    # major = models.ForeignKey(
    #     "ehr.Em_Major",
    #     verbose_name="人员专业",
    #     on_delete=models.CASCADE,
    #     null=True,
    #     blank=True,
    #     help_text="人员专业",
    # )
    pro_title = models.TextField(verbose_name="职称名称", null=True)
    pro_major = models.CharField(verbose_name="职称专业", null=True, blank=True, help_text="职称专业", max_length=100)
    is_superuser = models.BooleanField(default=False, verbose_name="是否超级用户", help_text="是否超级用户")
    phone = models.CharField(verbose_name="电话", max_length=40, null=True, blank=True)
    bank_card = models.CharField(verbose_name="银行卡号", max_length=40, null=True, blank=True)
    bank_name = models.CharField(verbose_name="银行名称", max_length=200, null=True, blank=True)
    jianxi_st_time = models.DateField(verbose_name="见习/试用开始时间", null=True, blank=True, help_text="见习/试用开始时间")
    jianxi_ed_time = models.DateField(verbose_name="见习/试用结束时间", null=True, blank=True, help_text="见习/试用结束时间")
    # 正序排列
    order_num = models.IntegerField(verbose_name="排序号", help_text="排序号", default=1, blank=True)
    user = models.ForeignKey(
        UserProfile,
        on_delete=models.SET_NULL,
        verbose_name="关联用户",
        help_text="关联用户",
        null=True,
        blank=True,
    )
    resignation_date = models.DateField(verbose_name="离职日期", null=True, blank=True, help_text="离职日期")

    class Meta:
        db_table = "sys_em_basic"
        # 站点管理显示名称
        verbose_name = "员工信息"
        # 站点管理复数显示名称
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.emp_name}"


class CodeManage(BaseModel):
    """编码"""

    name = models.CharField(max_length=100, verbose_name="名称", null=True, blank=True)
    app = models.CharField(max_length=200, verbose_name="应用", null=True, blank=True)
    model = models.CharField(max_length=200, verbose_name="模型", null=True, blank=True)
    field = models.CharField(max_length=100, verbose_name="字段", null=True, blank=True)
    rule = models.TextField(verbose_name="规则", null=True, blank=True)
    sequence_len = models.IntegerField(verbose_name="序列长度", default=4, blank=True)
    is_active = models.BooleanField(verbose_name="是否启用", default=False)
    anchor_point = models.CharField(max_length=100, verbose_name="键值", null=True, blank=True)

    class Meta:
        db_table = "sys_code_manage"
        verbose_name = "编码管理"
        verbose_name_plural = verbose_name


class LoginInfor(BaseModel):
    session_id = models.CharField(max_length=64, verbose_name="会话标识", null=True, blank=True)
    browser = models.CharField(max_length=64, verbose_name="浏览器")
    ipaddr = models.CharField(max_length=32, verbose_name="ip地址", null=True, blank=True)
    loginLocation = models.CharField(max_length=64, verbose_name="登录位置", null=True, blank=True)
    msg = models.TextField(verbose_name="操作信息", null=True, blank=True)
    os = models.CharField(max_length=64, verbose_name="操作系统", null=True, blank=True)
    status = models.BooleanField(default=False, verbose_name="登录状态")

    class Meta:
        db_table = "sys_loginlog"
        verbose_name = "登录日志"
        verbose_name_plural = verbose_name

    def __str__(self):
        return ""
        # return f"{self.creator and self.creator.name}"
